#!/bin/bash
set -euo pipefail
# 检查是否以root权限运行
if [ "$(id -u)" -ne 0 ]; then
    echo "错误：安装需要管理员权限，请使用sudo或切换到root用户。" >&2
    exit 1
fi
# 定义颜色代码(兼容POSIX)
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'
# 兼容性control文件查找(不使用数组)
find_control_file() {
    local pkg=${PACKAGE:-$1}
    local paths="
        ${DPKG_MAINTSCRIPT_DIR:-/var/lib/dpkg/tmp.ci}/control
        /var/lib/dpkg/info/${pkg}.control
        /var/lib/dpkg/info/${pkg}.list
        $(dirname "$0")/../control
        /usr/share/doc/${pkg}/control
        /DEBIAN/control
        "
    for path in $paths; do
        [ -f "$path" ] && { echo "$path"; return 0; }
    done
    return 1
}

PACKAGE=${PACKAGE:-${1:-}}
CONTROL_FILE=$(find_control_file "$PACKAGE") || {
    echo -e "${RED}错误：无法定位control文件${NC}" >&2
    exit 1
}

PACKAGE=$(awk -F':[[:space:]]+' '/^Package:/{print $2; exit}' "$CONTROL_FILE")
VERSION=$(awk -F':[[:space:]]+' '/^Version:/{print $2; exit}' "$CONTROL_FILE")
[ -z "$PACKAGE" ] && { echo -e "${RED}错误：无法解析包名${NC}" >&2; exit 1; }
[ -z "$VERSION" ] && { echo -e "${RED}错误：无法解析版本号${NC}" >&2; exit 1; }

case "${1:-install}" in
    upgrade|install|reinstall)
        if command -v dpkg-query >/dev/null; then
            OLD_VERSION=$(dpkg-query -W -f='${Version}' "$PACKAGE" 2>/dev/null || true)
            if [ -n "$OLD_VERSION" ]; then
                if dpkg --compare-versions "$OLD_VERSION" eq "$VERSION"; then
                    echo -e  "${YELLOW}提示：相同版本 ($VERSION)${NC}" >&2
                elif dpkg --compare-versions "$OLD_VERSION" lt "$VERSION"; then
                    echo -e  "${GREEN}升级: $OLD_VERSION -> $VERSION${NC}"
                else
                    echo -e  "${RED}降级: $OLD_VERSION -> $VERSION${NC}" >&2
                    export FORCE_DOWNGRADE=1
                fi
            fi
        fi
        ;;
    *) echo -e "${RED}错误：不支持的操作类型 ${1:-}[install|upgrade|reinstall]${NC}" >&2; exit 1 ;;
esac
if pgrep -x "$PACKAGE" >/dev/null; then
    echo -e "${BLUE}停止进程: $PACKAGE${NC}"
    pkill -x "$PACKAGE" || true
    sleep 2
fi
[ "${FORCE_DOWNGRADE:-0}" = "1" ] && {
    echo -e "${YELLOW}正在执行降级预处理...${NC}"
    rm -f /var/lib/dpkg/info/${PACKAGE}.* 2>/dev/null || true
}
exit 0